const { getDetail } = require("../service/get-detail");
const { getIndex } = require("../service/get-index");
const { compileHtml, getStatic } = require("../util/util");
const fse = require("fs-extra");
const path = require("path");

const captureAreticle = async (maxPage, startPage) => {
	for (let i = 1; i <= maxPage; i++) {
		try {
			let indexData = await getIndex({ page: i });

			for (let i = 0; i < indexData.listdata.length; i++) {
				try {
					let { id, addtime, title, thumb } = indexData.listdata[i];
					let detailData = await getDetail({
						id,
						isReplace: false
					});
					addtime = detailData.detail.addtime;
					let detailContent = detailData.detail.content;
					let detailMusic = detailData.detail.music;
					let detailThumb = detailData.detail.thumb;
					let detailTitle = detailData.detail.title+id;
					let detailVideo = detailData.detail.video;
					let detailClickNum = detailData.detail.click;
					detailTitle =
						detailTitle.replace([/[\/\\\\\:\*\?\<\>\|]/g, "-"]) +
						id;
					let fileFolder = path.resolve(
						__dirname,
						`../tmp/${addtime}/${detailTitle}`
					);
					let fileName = path.resolve(
						__dirname,
						`../tmp/${addtime}/${detailTitle}/${detailTitle}.txt`
					);
					fse.ensureDirSync(fileFolder);
					fse.ensureFileSync(fileName);
					try {
						await getStatic({
							url: detailMusic,
							filePath: fileFolder + `/detail-music${id}`
						});
					} catch (error) {}
					try {
						await getStatic({
							url: detailThumb,
							filePath: fileFolder + `/detail-thumb${id}`
						});
					} catch (error) {}

					fse.appendFileSync(
						fileName,
						`点击次数=>${detailClickNum}\r\n`
					);
					fse.appendFileSync(fileName, `封面图=>${detailThumb}\r\n`);
					fse.appendFileSync(fileName, `标题=>${detailTitle}\r\n`);
					fse.appendFileSync(fileName, `视频${detailVideo}\r\n`);
					fse.appendFileSync(
						fileName,
						`\r\n\r\n内容\r\n${detailContent}\r\n`
					);
				} catch (error) {
					continue;
				}
			}
		} catch (error) {
			continue;
		}
	}
};

module.exports = {
	captureAreticle
};
